package com.ylsf.blog.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ylsf.blog.exception.OverLastPageException;
import com.ylsf.blog.pojo.Article;
import com.ylsf.blog.pojo.ArticleComment;
import com.ylsf.blog.pojo.Comment;
import com.ylsf.blog.pojo.User;
import com.ylsf.blog.service.ListService;
import com.ylsf.blog.service.LoginService;
import com.ylsf.blog.service.impl.ListServiceImpl;
import com.ylsf.blog.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 博客主页控制类
 */
@WebServlet("/list")
public class ListServlet extends HttpServlet {
    private LoginService loginService=new LoginServiceImpl();
    private ListService listService=new ListServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //获取用户名和当前所在页数
        String username = request.getParameter("username");
        Integer pageStart = Integer.valueOf(request.getParameter("page"));
        //计算该用户的博客页数
        Integer listPage = listService.computeListPage(username);
        //根据名称查询用户信息
        User user = loginService.selectByUsername(username);
        //查询该用户的所有博客信息
        List<ArticleComment> articles = listService.displayUserArticles(username, pageStart);
        //转换为json对象
        String articleJson = JSON.toJSONString(articles);
        JSONObject result = new JSONObject();
        result.put("listPage", listPage);
        result.put("articles", JSON.parseArray(articleJson));
        //将结果转换为字符串并发送到前端
        String resultJson = JSON.toJSONString(result);
        System.out.println(resultJson);
        response.getWriter().print(resultJson);
    }
}
